package com.openNetty.common.utils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 加密工具
 *
 * @version 1.0.0
 * @author zhenggm
 */
public class DesUtil {
    private static final int KEY = 0x99;

    /**
     * 文件file进行加密并保存目标文件destFile中
     *
     * @param file     要加密的文件 如c:/test/srcFile.txt
     * @param destFile 加密后存放的文件名 如c:/加密后文件.txt
     */
    public static void encrypt(String file, String destFile) throws Exception {
        InputStream is = new FileInputStream(file);
        OutputStream out = new FileOutputStream(destFile);
        byte[] buffer = new byte[1024];
        byte[] bytes2 = new byte[1024];
        int r;
        while ((r = is.read(buffer)) > 0) {
            for (int i = 0; i < r; i++) {
                bytes2[i] = (byte) (buffer[i] ^ KEY);
            }
            out.write(bytes2, 0, r);
        }
        is.close();
        out.close();
    }

    /**
     * 文件file进行解密并保存目标文件destFile中
     *
     * @param file     要加密的文件 如c:/test/srcFile.txt
     * @param destFile 加密后存放的文件名 如c:/加密后文件.txt
     */
    public static void decrypt(String file, String destFile) throws Exception {
        InputStream is = new FileInputStream(file);
        OutputStream out = new FileOutputStream(destFile);
        byte[] buffer = new byte[1024];
        byte[] bytes2 = new byte[1024];
        int r;
        while ((r = is.read(buffer)) > 0) {
            for (int i = 0; i < r; i++) {
                bytes2[i] = (byte) (buffer[i] ^ KEY);
            }
            out.write(bytes2, 0, r);
        }
        is.close();
        out.close();
    }


//    public static void main(String[] args) throws Exception {
//        // td.encrypt("/Users/xiaomin/soft/sqlback-2017-10-132.tar.gz", "/Users/xiaomin/soft/encfile/encSqlback-2017-10-13.tar.gz"); //加密
//        encrypt("/Users/xiaomin/soft/back/encfile/encSqlback-2017-10-13.tar.gz", "/Users/xiaomin/soft/back/encSqlback-2017-10-114.tar.gz"); //解密
//        //  td.encrypt("/Users/xiaomin/soft/logo.jpg", "/Users/xiaomin/soft/encfile/logo.jpg"); //加密
//        // td.decrypt("/Users/xiaomin/soft/encfile/encSqlback-2017-10-13.tar.gz", "/Users/xiaomin/soft/encfile/encSqlback-2017-10-114.tar.gz"); //解密
//
//    }
}
